import $api from '@/common/request/index'
import $helpers from '@/common/utils/helpers.js';
import $storageKeyEnum from '@/common/enum/storage-key.enum.js'
// #ifdef  MP-WEIXIN || MP-ALIPAY
const accountInfo = uni.getAccountInfoSync();
// #endif
export default {


	// 获取服务供应商。如小程序是weixin，支付宝是alipay
	getProvider(callback) {
		uni.getProvider({
			service: 'oauth',
			success: function(res) {
				// console.log("provider：")
				callback(res.provider[0])
			}
		});
	},

	// 统一获取登录用户信息入口
	generalLogin(inProvider) {
		// #ifdef  H5
		uni.navigateTo({
			url: '/pages-logo/logo/logo' // 注意路径要正确
		});
		// #endif
		if (inProvider == 'weixin' || inProvider == 'toutiao') {
			this.uniAppletLogin(inProvider);
		} else if (inProvider == 'alipay') {
			this.aliPayLogin();
		} else {
			getApp().err('获取信息不成功，inProvider不存在');
		}
	},

	// 获取微信、头条小程序用户基础信息-前
	uniAppletLogin(inProvider) {

		// console.log(inProvider)
		if (inProvider == null || inProvider.length == 0) {
			getApp().err('provider参数有误：' + inProvider);
			return
		}

		var that = this;
		uni.login({
			provider: inProvider,
			success: function(loginRes) {
				// console.log('code:');
				// console.info(JSON.stringify(loginRes));
				// {"errMsg":"login:ok","code":"083Hrx000wvL*******0mXX6v1Hrx0l"}

				if (inProvider == 'weixin') {
					that.getWeiXinAppletUserInfo(loginRes.code);
				} else if (inProvider == 'toutiao') {
					that.getTouTiaoAppletUserInfo(loginRes.code);
				} else {
					getApp().err('获取信息不成功，inProvider不存在');
				}
			}
		});
	},

	// 获取微信小程序用户基础信息
	getWeiXinAppletUserInfo(code) {
		var that = this;
		let params = {
			code: code
		}
		that.getWeChatAppletUserInfo(params);
	},

	// 获取头条小程序用户基础信息
	getTouTiaoAppletUserInfo(code) {
		var that = this;

		uni.getUserInfo({
			withCredentials: true,
			success(res) {
				// console.log("getTouTiaoAppletUserInfo-success：")
				// console.info(JSON.stringify(res));
				that.getTouTiaoAppletLogin(code, res.userInfo)
			},
			fail: function(res) {
				// getApp().err('用户不同意授权');
				// console.log("getTouTiaoAppletUserInfo-fail：")
				// console.log(res);
				//拒绝授权
				return;
			}
		})
	},

	// 获取支付宝小程序用户基础信息-前
	aliPayLogin() {
		var that = this;
		//调用用户授权 API 获取用户信息
		my.getAuthCode({
			scopes: 'auth_base',
			success: (res) => {
				if (res.authCode) {
					var param = {
						authCode: res.authCode
					}
					that.getAliPayAppletUserInfo(param)
				}
			},
		});
	},

	// 支付宝小程序——请求后端登录
	getAliPayAppletUserInfo(params) {
		params.appId = accountInfo.miniProgram.appId;
		$api('member.aliLogin', params)
			.then(res => {
				if (res.status == 0 && res.data != null) {
					let memberInfo = res.data;
					this.userInfoBack(memberInfo)
				} else {
					getApp().err('登录失败，' + res.msg);
				}
			})
			.catch(() => {
				uni.hideLoading();
			});
	},

	// 微信小程序——请求后端登录
	getWeChatAppletUserInfo(params) {
		params.appId = accountInfo.miniProgram.appId;
		$api('member.login', params).then(res => {
				if (res.status == 0 && res.data != null) {
					let memberInfo = res.data;
					this.userInfoBack(memberInfo)
				} else {
					getApp().err('登录失败，' + res.msg);
				}
			})
			.catch(() => {
				uni.hideLoading();
			});
	},

	// 头条小程序——请求后端登录
	getTouTiaoAppletLogin(code, data) {
		const param = {
			touTiaoCode: code,
			nickName: data.nickName,
			headImgUrl: data.avatarUrl,
			appId: accountInfo.miniProgram.appId,
		}

		$api('member.touTiaoLogin', param)
			.then(res => {
				if (res.status == 0 && res.data != null) {
					let memberInfo = res.data;
					this.userInfoBack(memberInfo)
				} else {
					getApp().err('登录失败，' + res.msg);
				}
			})
			.catch(() => {
				uni.hideLoading();
			});
	},

	
	// 微信、支付宝登录后根据token获取用户信息
	getH5Login(token) {
		$helpers.setCache($storageKeyEnum.token_cache, token)
		$api('member.info', null).then(res => {
				uni.stopPullDownRefresh();
				if (res.status == 0) {
					let memberInfo = res.data;
					memberInfo.token = token;
					this.userInfoBack(memberInfo)
				} else {
					getApp().err("会员数据加载不成功_2：" + res.msg);
				}
			
			}).catch(err => {
				uni.hideLoading();
			})
	},

	// 登录后处理
	userInfoBack(memberInfo) {
		$helpers.setCache($storageKeyEnum.token_cache, memberInfo.token)
		memberInfo.token = null;
		$helpers.setCache($storageKeyEnum.member_info, memberInfo)

		//获取所有页面栈实例列表
		let pages = getCurrentPages();
		//当前页页面实例
		let nowPage = pages[pages.length - 1];
		if (
			nowPage.route.endsWith("pages-activity/activity-detail/activity-detail") ||
			nowPage.route.endsWith("pages-pay/recharge-package/recharge-package") ||
			nowPage.route.endsWith("pages-activity/pay-order/pay-order")
		) {
			return;
		}

		setTimeout(() => {
			if (nowPage.route.endsWith("pages/member/member-center/member-center")) {
				// console.log("login后onShow()")
				nowPage.onShow();
			} else if (nowPage.route.endsWith("pages/work-wx/receive-bi/receive-bi")) {
				//领券页面 ,判断是否是新用户
				nowPage.$vm.loginReturn();
			} else if (nowPage.route.endsWith("pages-pay/purchase-package/purchase-package")){
				nowPage.$vm.getOneDiscountPackage();
			} else if (nowPage.route.endsWith("pages-pay/recharge-package/recharge-package")){
				nowPage.$vm.getRechargePackageInfo();
			} else if (nowPage.route.endsWith("entrance-of-exchange-mall")){
				nowPage.$vm.findMemberInfo();
			} else if (nowPage.route.endsWith("pages-pay/android-vendmach-pay/android-vendmach-pay")) {
				nowPage.$vm.find();
			} else if (nowPage.route.endsWith("pages-pay/camera-pay/camera-pay")) {
				nowPage.$vm.find();
			}else {
				// console.log("login后onLoad()")
				// #ifdef MP-WEIXIN
				nowPage.onLoad();
				//#endif
				// #ifdef MP-ALIPAY
				nowPage.onReady();
				//#endif
			}
		}, 1000);
	},
}
